package com.mh.mh.netty.monitor;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.internal.StringUtil;

/**
 * 通用handler，处理IO事件
 * SimpleChannelInboundHandler 服务端用的
 * @author Administrator
 */
@ChannelHandler.Sharable// Sharable 为了线程安全
public class HandlerServerHelloEvent extends ChannelInboundHandlerAdapter {

    // 通道数组，保存所有注册到EventLoop的通道
    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        System.out.println("收到客户端发来的消息"+in.toString(CharsetUtil.UTF_8));

        ctx.writeAndFlush(Unpooled.copiedBuffer("你好，我是服务端，我已收到你的消息", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        /**
         * 处理IO异常
         */
        cause.printStackTrace();
        ctx.close();
    }


    /**
     * 新增连接
     * 如果连接建立成功以后，就会出发这个地方
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("客户端"+incoming.remoteAddress()+"已经连接上来");
        channels.add(incoming);
    }

    /**
     * 先掉线，再断开
     * 连接断开时，触发动作
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("客户端"+incoming.remoteAddress()+"已断开");
        channels.remove(incoming);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 通道处于活动状态触发的动作，该方法只会在通道建立时调用一次
        Channel incoming = ctx.channel();
        System.out.println("客户端"+incoming.remoteAddress()+"在线");

        String data = "aaaaaaaaaa";
        ctx.writeAndFlush(Unpooled.copiedBuffer("这是服务端在Active中的反馈"+data, CharsetUtil.UTF_8));

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 通道处于活动状态触发的动作，该方法只会在通道建立时调用一次
        Channel incoming = ctx.channel();
        System.out.println("客户端"+incoming.remoteAddress()+"掉线");
    }
}
